#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

# A few helpful tips about the Rules file:
#
# * The string given to #compile and #route are matching patterns for
#   identifiers--not for paths. Therefore, you can’t match on extension.
#
# * The order of rules is important: for each item, only the first matching
#   rule is applied.
#
# * Item identifiers start and end with a slash (e.g. “/about/” for the file
#   “content/about.html”). To select all children, grandchildren, … of an
#   item, use the pattern “/about/*/”; “/about/*” will also select the parent,
#   because “*” matches zero or more characters.

thumb_size='320x200'
images_per_page = @config[:images_per_page]

preprocess do
  if @config[:test] == true then
    puts; puts; puts
    puts "================================================"
    puts "** Warning : this site is configured for test **"
    puts "**             DO NOT deploy it!              **"
    puts "================================================"
    puts; puts; puts
  end

  # Auto generation of thumbbails
  unless Dir.exists?('output/tn')
    Dir.mkdir('output/tn')
    puts "'output/tn' directory created"
  end
  Dir.glob('content/caps/*.png').select do |f|
    fn=File.basename(f)
    if not File.exists?("output/tn/#{fn}")
      puts "creating thumbnails for #{f}"
      system("convert #{f} -resize #{thumb_size} output/tn/#{fn}")
    end
  end

  # Creating tmp/ directory if it doesn't exist
  unless Dir.exists?('tmp')
    Dir.mkdir('tmp')
    puts "'tmp' directory created"
  end
  
  # Generate a YAML file in tmp/ that contains list of images
  # per person's slug
  imgs_per_p = Hash.new
  uniq_persons().each do |p|
    imgs_per_p[slug_for(p)] = Array.new # This array will contains images
 
    @items.each do |j|
      # Because a news can contain no imagelist...
      if not j[:imagelist].nil?
        j[:imagelist].each do |ili|
          name = ili[:name]
          if slug_for(p) == slug_for(name) then
            # We simply copy values from image to imgs_per_p ...
            img = Hash.new
            img[:file] = ili[:file]
            img[:title] = ili[:title]
            img[:tags] = ili[:tags]
            img[:name] = ili[:name]
            # ... and append these values to the person's hash
            imgs_per_p[slug_for(name)] << img unless name.nil?
          end
        end
      end
    end
  end
  # Finally write the file in tmp/
  File.open("tmp/images_per_person.yml", "w") do |f|
    f.write imgs_per_p.to_yaml
  end

  # Person individual page generation
  uniq_persons().each do |p|
    pagination_hash = Hash.new
    pagination_hash[:slug] = "personnalite/#{slug_for(p)}"

    images = person_image_list(slug_for(p))
    nb_images = images.size
    nb_pages = (nb_images / images_per_page) +1
    nb_pages=1 if nb_images == images_per_page
    content = ""

    puts "#{p}: #{nb_images} soit #{nb_pages} pages."

    if nb_pages == 1 then
      pagination_hash[:page] = 1
      pagination_hash[:total_page] = 1
      pagination_hash[:previous] = false
      pagination_hash[:next] = false
      opts = { :title => "#{p}",  :pagination => pagination_hash}
      @items << Nanoc::Item.new(content, opts, "/personnalite/#{slug_for(p)}/" )
    else
      pagination_hash[:total_page] = nb_pages
      # Generates the redirect page
      opts = { :title => "#{p}",  :layout => 'personnalite_redirect'}
      @items << Nanoc::Item.new(content, opts, 
                                "/personnalite/#{slug_for(p)}")

      # Generate each page containing images
      [*1..nb_pages].each do |page|
        pagination_hash[:page] = page
        pagination_hash[:previous] = (not page == 1)
        pagination_hash[:next] = (not page == nb_pages)

        opts = { :title => "#{p}",  :pagination => pagination_hash}
        @items << Nanoc::Item.new(content, opts, 
                                  "/personnalite/#{slug_for(p)}-page-#{page}")
       
      end
    end
  end
end

compile '/stylesheet/' do
  # don’t filter or layout
end

compile '/caps/' do
  # don’t filter or layout
end

compile /news/ do
  if item.binary?
    # don’t filter binary items
  else
    filter :kramdown, :auto_ids => false
    layout 'news'
  end
end

compile /tags/ do
  filter :erb, :auto_ids => false
  layout 'tags'
end

compile /personnalite/ do
  filter :erb, :auto_ids => false
  # Here we test for already set layout (i.e. personnalite-redirect)
  if @item[:layout].nil?
    layout 'personnalite' 
  else
    layout @item[:layout]
  end
end

compile '/js/*' do
  # don’t do anything
end

compile '/caps/htaccess/' do
  filter :erb
  layout 'htaccess'
end

compile 'sitemap' do
  filter :erb
end

compile '*' do
  if item.binary?
    # don’t filter binary items
  else
    filter :erb
    layout item[:layout] || 'default'
  end
end

route '/stylesheet/' do
  '/style.css'
end

route '/news/*NOT_ADDED' do
  nil
end

# Simply copy files
route '/js/*' do
  # conditionnal to avoid setup LICENSES files in output, only route .js
  if item[:extension] =~ /.*js$/
    item.identifier.chop + '.' + item[:extension] 
  end
end

route '/caps/htaccess/' do
  '/caps/.htaccess'
end

compile '/sitemap/' do
  filter :erb
  layout 'htaccess'
end

route 'sitemap' do
  item.identifier.chop + '.xml'
end

route 'robots' do
  item.identifier.chop + '.txt'
end

route '*' do
  if item.binary?
    # Write item with identifier /foo/ to /foo.ext
    item.identifier.chop + '.' + item[:extension]
  else
    # Write item with identifier /foo/ to /foo/index.html
    item.identifier + 'index.html'
  end
end

layout '*', :erb
